package com.impress;

import java.util.ArrayList;
import java.util.List;

import com.impress.adapter.BannerItemsAdapter;
import com.impress.adapter.DetailItemsAdapter;
import com.impress.listener.OnScrollListener;
import com.impress.model.Item;
import com.impress.provider.FeedData;
import com.impress.service.ItemService;
import com.mobclick.android.MobclickAgent;
import com.mobclick.android.ReportPolicy;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;

public class ItemsViewActivity extends Activity {

	private FeedGallery mItemsGallery;
	private Gallery mBannerGallery;
	private SlidingDrawer mSlidingDrawer;
	private TextView mTextView;
	private TitleBar mTitleBar;
	
	private ItemService mItemService = new ItemService(this);
	
	private DetailItemsAdapter mDetailItemsAdapter;
	private BannerItemsAdapter mBannerItemsAdapter;
	private List<Item> mItems;
	@Override
	protected void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		
		MobclickAgent.onError(this);
		MobclickAgent.setReportPolicy(ReportPolicy.DAILY);
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.items_view);
		mItemsGallery = (FeedGallery)findViewById(R.id.items_detail_gallery);
		mBannerGallery = (Gallery)findViewById(R.id.item_gallery);
		mSlidingDrawer = (SlidingDrawer)findViewById(R.id.item_view_banner);
		mSlidingDrawer.open();
		mTextView = (TextView)findViewById(R.id.item_view_feed_title);
		mSlidingDrawer.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener() {
			
			@Override
			public void onDrawerOpened() {
				mTitleBar.setVisibility(View.VISIBLE);				
			}
		});
		mSlidingDrawer.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() {
			
			@Override
			public void onDrawerClosed() {
				mTitleBar.setVisibility(View.GONE);				
			}
		});
			
		mTitleBar=(TitleBar)findViewById(R.id.titlebar);
		mTitleBar.setViewState(Utility.VIEW_STATE_ITEM);
		mTitleBar.setBackListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				backToFeed();
				return false;
			}
		});
		Bundle bundle = getIntent().getExtras();
		
		int selecteditem = bundle.getInt("selectedItem");
		ArrayList list = bundle.getParcelableArrayList("list");
		if(list!=null){
			mItems = (ArrayList<Item>)list.get(0);
			mTextView.setText(mItems.get(0).getFeedTitle());
		}else{
			mItems = new ArrayList<Item>();
		}
		mDetailItemsAdapter = new DetailItemsAdapter(this, mItems,onScrollListener);
		mBannerItemsAdapter = new BannerItemsAdapter(this, mItems);
		mItemsGallery.setAdapter(mDetailItemsAdapter);
		mItemsGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				Item item = (Item)mDetailItemsAdapter.getItem(position);
				mBannerGallery.setSelection(position);
				item.setReadStatePending(1);
				mItemService.updateItemState(item, FeedData.Items.READ_STATE_PENDING, 1);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		});
		mBannerGallery.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				mItemsGallery.setSelection(position);
				
			}
		});
		mItemsGallery.setSelection(selecteditem);
		mBannerGallery.setAdapter(mBannerItemsAdapter);
		mBannerGallery.setSelection(selecteditem);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.clear();
		getMenuInflater().inflate(R.menu.article_options_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		int selected = mItemsGallery.getSelectedItemPosition();
		if(selected<0 || selected>=mItems.size()){
			return false;
		}
        Item item = (Item)mDetailItemsAdapter.getItem(selected);
        menu.findItem(R.id.mark_as_read_menu_item).setVisible(!item.isRead());
        menu.findItem(R.id.mark_as_unread_menu_item).setVisible(item.isRead());
        menu.findItem(R.id.share_in_GR_menu_item).setVisible(!item.isShare());
        menu.findItem(R.id.unshare_menu_item).setVisible(item.isShare());
        menu.findItem(R.id.like_menu_item).setVisible(!item.isLike());
        menu.findItem(R.id.unlike_menu_item).setVisible(item.isLike());

		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int selected = mItemsGallery.getSelectedItemPosition();
		if(selected<0 || selected>=mItems.size()){
			return false;
		}
        Item selectedItem = (Item)mDetailItemsAdapter.getItem(selected);
		switch (item.getItemId()) {
		case R.id.mark_as_read_menu_item:
            selectedItem.setReadStatePending(1);
            break;
    case R.id.mark_as_unread_menu_item:
            selectedItem.setReadStatePending(0);
            break;
    case R.id.share_in_GR_menu_item:
            selectedItem.setShareStatePending(1);
            break;
    case R.id.unshare_menu_item:
            selectedItem.setShareStatePending(0);
            break;
    case R.id.like_menu_item:
            selectedItem.setLikeStatePending(1);
            break;
    case R.id.unlike_menu_item:
            selectedItem.setLikeStatePending(0);
            break;
    case R.id.send_article_menu_item:
            Intent send = new Intent(Intent.ACTION_SEND);
            send.setType("text/plain");
            String content = selectedItem.getTitle()+selectedItem.getAlternateUrl();
            send.putExtra(Intent.EXTRA_TEXT, content);
            send.putExtra(Intent.EXTRA_SUBJECT, getText(R.string.sendShareTitle));
            startActivity(send);
            break;


		default:
			break;
		}
		mItemService.updateItemState(selectedItem);
		return super.onOptionsItemSelected(item);
	}

	private OnScrollListener onScrollListener = new OnScrollListener() {
		
		@Override
		public void ScrollToBottom() {
			if(!mSlidingDrawer.isOpened())
				mSlidingDrawer.animateOpen();
		}

		@Override
		public void Scrolling() {
			mTitleBar.setVisibility(View.GONE);
//			mBannerGallery.setVisibility(View.GONE);
			if(mSlidingDrawer.isOpened())
				mSlidingDrawer.animateClose();
		}

		@Override
		public void SingleTaped() {
			if (mTitleBar.getVisibility() == View.GONE) {
                mTitleBar.setVisibility(View.VISIBLE);
        }else {
                mTitleBar.setVisibility(View.GONE);
        }
			mBannerGallery.setVisibility(mTitleBar.getVisibility());
		}
	};
	
	public class CommonGesture extends SimpleOnGestureListener{

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			if(Math.abs(e1.getX()-e2.getX())>100 && Math.abs(velocityX)>20){
				return mItemsGallery.onFling(e1, e2, velocityX, velocityY);
			}
			return super.onFling(e1, e2, velocityX, velocityY);
		}

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2,
				float distanceX, float distanceY) {
//			if(e1.getX()-e2.getX()>100 ){
//				return mItemsGallery.onScroll(e1, e2, distanceX, distanceY);
//			}else if(e1.getX()-e2.getX()<-100 ){
//				return mItemsGallery.onScroll(e1, e2, distanceX, distanceY);
//			}
			double x = Math.abs(e1.getX()-e2.getX());
			double y = Math.abs(e1.getY()-e2.getY());
			if(x>(1.73*y)){
				Log.d("View", "gallery scroll");
				return mItemsGallery.onScroll(e1, e2, distanceX, distanceY);
			}
			Log.d("View", "gesture scroll");
			return super.onScroll(e1, e2, distanceX, distanceY);
		}
		
	}

	private void backToFeed(){
		Intent intent = getIntent();
		setResult(RESULT_OK, intent);
		ItemsViewActivity.this.finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
			if(!mSlidingDrawer.isOpened()){
				mSlidingDrawer.animateOpen();
				return false;
			}else{
			backToFeed();
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	

}
